package com.wechat.android.app.db;

import android.content.Context;

import com.wechat.android.app.entity.UserInfoModel;
import com.wechat.android.app.global.Constants;
import com.wechat.android.app.utils.GsonUtils;
import com.wechat.android.app.utils.JsonUtil;
import com.wechat.android.app.utils.MD5;
import com.wechat.android.app.utils.MyLog;
import com.wechat.android.app.utils.SharedPreferencesUtils;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

/**
 * Created by wangyang on 2017/12/12 0030..
 */
public class UserHelper {
    private final String TAG = getClass().getSimpleName();
    private static UserHelper mInstance = null;
    private DbManager db = null;
    private String userAccount = null;
    private String userPassword = null;
    private String AUTH_KEY = null;         //MD5(UserName+APPName+UserPassword)
    private boolean isLogined = false;
    private UserTable mUser = null;
    private UserInfoModel mUserInfoModel = null;
    public static synchronized UserHelper getInstance() {
        if (mInstance == null) {
            mInstance = new UserHelper();
        }
        return mInstance;
    }



    public String getAuthKey() {
        return AUTH_KEY;
    }

    public String getAuthKeyFromStorage(Context mContext) {
        return (String) SharedPreferencesUtils.getParam(mContext, userAccount + Constants.SHARED_PREFERENCES_KEY_AUTH_KEY_STORAGE, "");
    }

    public void saveUserAuth(String userName, String userPassword) {
        saveUserAuth(userName, userPassword, false);
    }

    public void saveUserAuth(String userName, String userPassword, boolean isGenerateAuthKey) {
        if (db == null) {
            db = DbHelper.getInstance().getDb();
        }
        try {
            UserTable tmpUser = db.selector(UserTable.class).where("useraccount", "=", userName).findFirst();

            if (tmpUser == null) {
                UserTable user = new UserTable();
                user.setUserAccount(userName);
                user.setUserPassword(userPassword);
                user.setLastLoginTime(System.currentTimeMillis());
                db.saveOrUpdate(user);
            } else {
                tmpUser.setUserAccount(userName);
                tmpUser.setUserPassword(userPassword);
                tmpUser.setLastLoginTime(System.currentTimeMillis());
                db.update(tmpUser);
            }

        } catch (DbException e) {
            e.printStackTrace();
        }
        if (isGenerateAuthKey) {
            generateAuthKey(userName, userPassword);

        }
    }

    public UserTable getLastLoginUser() {
        if (db == null) {
            db = DbHelper.getInstance().getDb();
        }
        try {
            mUser = db.selector(UserTable.class).where("lastlogintime", ">", System.currentTimeMillis() - 7 * 24 * 3600 * 1000).orderBy("lastlogintime", true).findFirst();
        } catch (DbException e) {
            e.printStackTrace();
        }
        if (mUser != null) {
            userAccount = mUser.getUserAccount();
            userPassword = mUser.getUserPassword();
        }
        return mUser;
    }

    public void generateAuthKey(String userName, String userPassword) {
        this.userAccount = userName;
        this.userPassword = userPassword;
        AUTH_KEY = MD5.getMD5Str(userName + Constants.APP_PREF + userPassword);
    }

    public void saveUserInfo(Context mContext, String data) {
        if (AUTH_KEY == null) {
            MyLog.e(TAG, "Please execute the 'generateAuthKey' method before running this method!");
        }
        SharedPreferencesUtils.setParam(mContext, userAccount + Constants.SHARED_PREFERENCES_KEY_AUTH_KEY_STORAGE, AUTH_KEY);
        //用户信息 userInfoModel
//        String userInfo = JsonUtil.getJsonValuesString(data, "user");
        SharedPreferencesUtils.setParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_USER_INFO_MODEL, data);
        mUserInfoModel = GsonUtils.getBean(data, UserInfoModel.class);


    }



    public boolean isLogined() {
        return isLogined;
    }

    public void setIsLogined(boolean b) {
        this.isLogined = b;
    }







    public UserInfoModel getUserInfoModel(Context mContext) {
        if (mUserInfoModel == null) {
            if (AUTH_KEY == null) {
                getLastLoginUser();
                if (mUser == null) {
                    return null;
                }
                generateAuthKey(mUser.getUserAccount(), mUser.getUserPassword());
            }
            if (AUTH_KEY == null || !AUTH_KEY.equals(getAuthKeyFromStorage(mContext))) {
                return null;
            } else {
                mUserInfoModel = GsonUtils.getBean((String) SharedPreferencesUtils.getParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_USER_INFO_MODEL, ""), UserInfoModel.class);
                MyLog.i(TAG, "mUserInfoModel is null:");
            }
        }
        return mUserInfoModel;
    }

    public void setUserInfoModel(UserInfoModel mUserInfoModel) {
        this.mUserInfoModel = mUserInfoModel;
    }

    public void setUserInfoModel(Context mContext, UserInfoModel mUserInfoModel) {
        this.mUserInfoModel = mUserInfoModel;
        SharedPreferencesUtils.setParam(mContext, AUTH_KEY + Constants.SHARED_PREFERENCES_KEY_USER_INFO_MODEL, GsonUtils.GsonToString(mUserInfoModel));
    }








    public String getUserAccount() {
        if (userAccount == null) {
            getLastLoginUser();
        }
        return userAccount;
    }

    public void setUserAccount(String userAccount) {
        this.userAccount = userAccount;
    }

    public String getUserPassword() {
        if (userPassword == null) {
            getLastLoginUser();
        }
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getAUTH_KEY() {
        return AUTH_KEY;
    }

    public void setAUTH_KEY(String AUTH_KEY) {
        this.AUTH_KEY = AUTH_KEY;
    }




}
